<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\CommonController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityRanking;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUserUnit;
use App\Models\Manage;
use App\Models\UserAddress;
use App\Models\UserDrawAddress;
use App\Models\UserInfo;
use App\Validate\AnswerActivityRankingValidate;
use Illuminate\Support\Facades\Cache;


/**
 * 活动排行榜管理
 */
class AnswerActivityRankingController extends CommonController
{

    public $model = null;
    public $activityModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityRanking();
        $this->activityModel = new AnswerActivity();
        $this->validate = new AnswerActivityRankingValidate();
    }

    /**
     * 活动排名
     * @param act_id int 活动id
     * @param unit_id int 单位id  除独立活动外，若传了则是单位排名，不传则是总排名  ；独立活动，单位排名等于独立排名
     * @param keywords int 检索条件  微信昵称（全匹配）
     * @param page int 页码
     * @param limit int 分页大小
     */
    public function ranking()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('ranking')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $act_info = $this->activityModel->detail($this->request->act_id, null, null);

        if (empty($act_info)) {
            return $this->returnApi(201, '参数错误');
        }

        if ($act_info['node'] == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(201, '此活动为独立活动，不允许选择单位');
        }

        //正式打开
        // $this->model->getExecuteResult($act_info['pattern'], $this->request->act_id); //获取转账执行结果

        $cache_key = md5($this->request->token . $this->request->act_id . $this->request->unit_id . $this->request->page . $this->request->limit . $this->request->keywords);
        $cache_rank = Cache::get($cache_key);

        if ($cache_rank) {
            return $this->returnApi(200, '获取成功', true, $cache_rank);
        }

        $userInfoModel = new UserInfo();
        $userDrawAddressModel = new UserDrawAddress();
        $activityUserUnitModel = new AnswerActivityUserUnit();

        if ($this->request->keywords) {
            //查询某个用户的排名
            //获取用户排名
            $user_guid = $userInfoModel->getUserGuidByKeywords($this->request->keywords);
            if (empty($user_guid)) {
                return $this->returnApi(203, '暂无数据');
            }
            $user_rank = $this->model->userRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, $user_guid);
            if (empty($user_rank['rank'])) {
                return $this->returnApi(203, '暂无数据');
            }
            $user_info = $userInfoModel->getWechatInfo($user_guid);
            $user_draw_address_info = $userDrawAddressModel->detail($user_guid, 1, $this->request->act_id);
            $user_address = $activityUserUnitModel->getUserUnitInfo($user_guid, $this->request->act_id);
            //组装数据
            $res['data'] = [
                [
                    'user_guid' => $user_guid,
                    'correct_number' => $user_rank['correct_number'],
                    'unit_name' => $activityUserUnitModel->getUnitName($this->request->act_id, $user_guid),
                    'accuracy' => $user_rank['accuracy'],
                    'create_time' => $user_rank['create_time'],
                    'change_time' => $user_rank['change_time'],
                    'user_wechat_info' => $user_info,
                    'rank' => $user_rank['rank'],
                    'user_draw_address_info' => $user_draw_address_info,
                    'user_unit_info' => $user_address,
                    'times' => $user_rank['times'],
                    'price' => $user_rank['price'],
                    'pay_time' => $user_rank['pay_time'],
                    'order_id' => $user_rank['order_id'],
                    'state' => $user_rank['state'],
                    'fail_reason' => $user_rank['fail_reason'],
                ]
            ];
            $res['data'][0][$this->list_index_key] = 1;

            $res['total'] = 1;
            $res['per_page'] = $this->request->limit;
            $res['current_page'] = 1;
            $res['last_page'] = 1;
        } else {
            $res = $this->model->getRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, $this->request->limit);

            if (empty($res['data'])) {
                return $this->returnApi(203, '暂无数据');
            }

            $res = $this->disPageData($res);

            $commonController = new CommonController();
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['unit_name'] = $activityUserUnitModel->getUnitName($this->request->act_id, $val['user_guid']);
                $res['data'][$key]['rank'] = $commonController->addSerialNumberOne($key, $this->request->page, $this->request->limit);
                $res['data'][$key]['user_wechat_info'] = $userInfoModel->getWechatInfo($val['user_guid']);
                $res['data'][$key]['user_draw_address_info'] = $userDrawAddressModel->detail($val['user_guid'], 1, $this->request->act_id);
                $res['data'][$key]['user_unit_info'] = $activityUserUnitModel->getUserUnitInfo($val['user_guid'], $this->request->act_id);
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
                $res['data'][$key]['times'] = second_to_time($val['times']);
            }
        }

        Cache::put($cache_key, $res, 60); //缓存一分钟

        return $this->returnApi(200, '获取成功', true, $res);
    }


    /**
     * 活动排名转账
     * 
     * @param content  json格式数据  [{"id":1,"rank":1,"act_id":1,"price":0.3,"user_guid":"92de8f1c61a84baf8cfea5371da19706"},{"id":2,"rank":2,"act_id":1,"price":0.3,"user_guid":"ad2c068454b67b5dd4ad6db2b2f99535"}]
     *                              * @param id 排名列表数据id
     *                              * @param rank 排名数字
     *                              * @param act_id 活动id
     *                              * @param user_guid 用户id 
     *                              * @param price 转账金额  单位 元  0.3~200 之间的数字
     * 
     * 数组格式
     *      $content = [
            ['id'=>1,'rank'=>1,'act_id'=>1,'price'=>0.3,'user_guid'=>'92de8f1c61a84baf8cfea5371da19706'],
            ['id'=>2,'rank'=>2,'act_id'=>1,'price'=>0.3,'user_guid'=>'ad2c068454b67b5dd4ad6db2b2f99535'],
        ];

     * @param login_password 登录密码
     */
    public function rankingTransfer()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('ranking_transfer')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //限制用户多次点击
        $key = md5('ranking_ransfer');
        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey) {
            return $this->returnApi(201, "10秒内只能发起一次转账，请稍后重试");
        } else {
            Cache::put($key, 1, 10);
        }

        $manageModel = new Manage();
        $is_super_admin = $manageModel->isSuperAdmin(); //是否是超级管理员

        $answer_activity_gift_type = config('other.answer_activity_gift_type');
        if (!in_array(1, $answer_activity_gift_type) || $is_super_admin !== true) {
            return $this->returnApi(202, '活动不支持红包转账功能');
        }


        //验证密码
        $validate_password = validate_password($this->request->login_password);
        if ($validate_password !== true) {
            return $this->returnApi(202, $validate_password);
        }
        $password = Manage::where('id', request()->manage_id)->where('is_del', 1)->value('password');
        if (empty($password)) {
            return $this->returnApi(202, '此账号不存在');
        }
        if ($password != md5($this->request->login_password)) {
            return $this->returnApi(202, '密码输入不正确');
        }

        //进行转账验证
        $res = $this->model->rankingTransfer($this->request->content);

        if (is_string($res)) {
            return $this->returnApi(202, $res);
        }
        return $this->returnApi(200, '操作成功', true, $res);
    }
}
